package com.collectplus.express.view;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Uses a combination of a PageTransformer and swapping X & Y coordinates
 * of touch events to create the illusion of a vertically scrolling ViewPager.
 * <p>
 * Requires API 11+
 */
public class VerticalViewPager extends ViewPager {
    /**
     * ViewPager管理的的页面
     */
    private List<View> items = new ArrayList<View>();

    public VerticalViewPager(Context context) {
        super(context);
        init();
    }

    public VerticalViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // The majority of the magic happens here  
        setPageTransformer(true, new VerticalPageTransformer());
        // The easiest way to get rid of the overscroll drawing that happens on the left and right  
        setOverScrollMode(OVER_SCROLL_NEVER);
    }

    private class VerticalPageTransformer implements ViewPager.PageTransformer {

        @Override
        public void transformPage(View view, float position) {

            if (position < -1) { // [-Infinity,-1)  
                // This page is way off-screen to the left.  
                view.setAlpha(0);

            } else if (position <= 1) { // [-1,1]  
                view.setAlpha(1);

                // Counteract the default slide transition  
                view.setTranslationX(view.getWidth() * -position);

                //set Y position to swipe in from top  
                float yPosition = position * view.getHeight();
                view.setTranslationY(yPosition);

            } else { // (1,+Infinity]  
                // This page is way off-screen to the right.  
                view.setAlpha(0);
            }
        }
    }

    /**
     * Swaps the X and Y coordinates of your touch event.
     */
    private MotionEvent swapXY(MotionEvent ev) {
        float width = getWidth();
        float height = getHeight();

        float newX = (ev.getY() / height) * width;
        float newY = (ev.getX() / width) * height;

        ev.setLocation(newX, newY);

        return ev;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
        swapXY(ev); // return touch coordinates to original reference frame for any child views  
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return super.onTouchEvent(swapXY(ev));
    }

    public void setFragmentItems(FragmentManager fm, Fragment... fragments) {
        ArrayList<Fragment> items = new ArrayList<Fragment>();
        items.addAll(Arrays.asList(fragments));
        setAdapter(new FragmentPagerAdapterExt(fm, items));
    }

    private class FragmentPagerAdapterExt extends FragmentPagerAdapter {
        private List<Fragment> fragmentsList;

        public FragmentPagerAdapterExt(FragmentManager fm) {
            super(fm);
        }

        public FragmentPagerAdapterExt(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragmentsList = fragments;
        }

        @Override
        public int getCount() {
            return fragmentsList.size();
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentsList.get(position);
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }

    }

    /**
     * C 'ABC' A <br>
     * 列表的首尾各增加一个元素 添加要显示页面到ViewPager <br>
     * {@link #setFragmentItems(FragmentManager, Fragment...)}
     */
    public void setViewItems(List<View> pages) {
        items.clear();
        items.addAll(pages);
        super.setAdapter(new PagerAdatperExt());
    }

    /**
     * ViewPager适配器(适合于普通的View)
     *
     * @author wangtaoyfx <br>
     *         2013-1-24上午9:33:55
     */
    private class PagerAdatperExt extends PagerAdapter {

        @Override
        public int getCount() {
            return items.size();
        }

        /**
         * 该方法必须被覆盖
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            Log.i("on__destroyItem", position + "");
            removeView(items.get(position % items.size()));
        }

        /**
         * 比较view与object是否为同一个对象，如果是则显示出胡来 如果不是则不显示 <br/>
         * object即instantiateItem(ViewGroup,position)返回的对象
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * java.lang.UnsupportedOperationException: Required method instantiateItem was not overridden
         * <p>
         * 显示当前ViewPager指定位置的视图 该方法必须被重载
         *
         * @param container
         * @param position
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Log.i("on__instantiateItem", position + "");
            int tmp = position % items.size();
            //
            // removeView(mItems.get(tmp));
            try {
                addView(items.get(tmp), 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return items.get(tmp);
        }
    }
}  
